package service;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.SeekBar;
import android.widget.Toast;

import com.lanou.horo.myapplication.R;
import com.lanou.horo.myapplication.dbdao.HistoryEntity;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

import dbdao.HistoryDBhelper;
import de.greenrobot.event.EventBus;
import utils.MessageEvent;
import utils.PlayMessage;
import volley.VolleySingleton;

/**
 * Created by dllo on 15/11/26.
 */
public class MusicService extends Service implements MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnPreparedListener {
    private ServiceBinder sb = new ServiceBinder();
    public MediaPlayer mediaPlayer; // 媒体播放器
    private SeekBar seekBar; // 拖动条
    private Timer mTimer = new Timer(); // 计时器
    private ServiceReceiver receiver;
    private NotificationManager manager;
    private RemoteViews remoteViews;
    NotificationCompat.Builder builder;
//    Message mes;


    public void setMSeekBar(SeekBar seekBar) {
        this.seekBar = seekBar;
    }

    // 计时器
    TimerTask timerTask = new TimerTask() {

        @Override
        public void run() {
            if (mediaPlayer == null)
                return;
            if (mediaPlayer.isPlaying() && seekBar.isPressed() == false) {
                handler.sendEmptyMessage(0); // 发送消息
            }
        }
    };
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            int position = mediaPlayer.getCurrentPosition();
            int duration = mediaPlayer.getDuration();
            if (duration > 0) {
                // 计算进度（获取进度条最大刻度*当前音乐播放位置 / 当前音乐时长）
                long pos = seekBar.getMax() * position / duration;
                seekBar.setProgress((int) pos);
            }
        }

        ;
    };


    @Override
    public void onCreate() {
        super.onCreate();


        try {
            receiver = new ServiceReceiver();//----注册广播
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(ServiceReceiver.NOTIFICATION_ITEM_BUTTON_LAST);
            intentFilter.addAction(ServiceReceiver.NOTIFICATION_ITEM_BUTTON_PLAY);
            intentFilter.addAction(ServiceReceiver.NOTIFICATION_ITEM_BUTTON_NEXT);
            registerReceiver(receiver, intentFilter);
            manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            EventBus.getDefault().register(this); //注册EventBus
            builder = new NotificationCompat.Builder(this);


            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);// 设置媒体流类型
            mediaPlayer.setOnBufferingUpdateListener(this);
            mediaPlayer.setOnPreparedListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 每一秒触发一次
        mTimer.schedule(timerTask, 0, 1000);

//        mes = h.obtainMessage();
//        mes.what = 1;
//        h.sendMessage(mes);


        new Handler(this.getMainLooper()).post(new Runnable() {

            @Override
            public void run() {
                // 在这里执行你要想的操作 比如直接在这里更新ui或者调用回调在 在回调中更新ui
                if (HistoryDBhelper.getInstance().queryAll() !=
                        null && HistoryDBhelper.getInstance().queryAll().size() > 0) {
                    HistoryEntity history = HistoryDBhelper.getInstance().queryAll().get(HistoryDBhelper.
                            getInstance().queryAll().size() - 1);
                    setCustomView(history.getNickname(), history.getTitle(), history.getSmallLogo());//设置数据
                } else {
                    setCustomView("累死我了", "累死我了", "http://fdfs.xmcdn.com/group6/M00/A9/16/wKgDhFUKmDeQ5wyYAAAeKv3qBXg090_mobile_large.jpg");
                }
                showCustomView();
            }
        });

    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);

    }


    @Override
    public boolean onUnbind(Intent intent) {
        manager.cancel(0);
        manager.cancelAll();
        unregisterReceiver(receiver);
        EventBus.getDefault().unregister(this);  //取消注册
        mediaPlayer.stop();
        return super.onUnbind(intent);
    }

//    @Override
//    public void onDestroy() {
//        Log.d("MusicService", "asdaa");
//        super.onDestroy();
//        manager.cancel(0);
//        manager.cancelAll();
//        EventBus.getDefault().unregister(this);  //取消注册
//        mediaPlayer.stop();
////        unregisterReceiver(receiver);
//    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return sb;
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        seekBar.setSecondaryProgress(percent);
        int currentProgress = seekBar.getMax()
                * mediaPlayer.getCurrentPosition() / mediaPlayer.getDuration();
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.start();
    }

    public class ServiceBinder extends Binder {
        public MusicService getService() {
            return MusicService.this;
        }
    }

    public void playNow(String url) {
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(url); // 设置数据源
            mediaPlayer.prepare(); // prepare自动播放
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void play() {
        mediaPlayer.start();
    }

    // 暂停
    public void pause() {
        mediaPlayer.pause();
    }

    // 停止
    public void stop() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
        }
    }

//    private Handler h = new Handler() {
//
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//
//            switch (msg.what) {
//                case 1:
//                    if (HistoryDBhelper.getInstance().queryAll() !=
//                            null && HistoryDBhelper.getInstance().queryAll().size() > 0) {
//                        HistoryEntity history = HistoryDBhelper.getInstance().queryAll().get(HistoryDBhelper.
//                                getInstance().queryAll().size() - 1);
//                        setCustomView(history.getNickname(), history.getTitle(), history.getSmallLogo());//设置数据
//                    } else {
//                        setCustomView("累死我了", "累死我了", "http://fdfs.xmcdn.com/group6/M00/A9/16/wKgDhFUKmDeQ5wyYAAAeKv3qBXg090_mobile_large.jpg");
//                    }
//                    showCustomView();
//                    break;
//                case 2:
//
//                    break;
//            }
//        }
//
//    };

    /**
     * 接收数据
     * 该方法在ui主线程执行
     */
    public void onEventMainThread(MessageEvent event) {
//        mes.what = 2;
//        h.sendMessage(mes);
        setCustomView(event.user, event.title, event.img);
        showCustomView();
    }

    /**
     * 设置通知栏数据
     */
    private void setCustomView(final String name, final String title, final String bit) {
        remoteViews = new RemoteViews(getPackageName(),
                R.layout.music_notification);
        remoteViews.setTextViewText(R.id.title_music_name, name); //设置主播
        remoteViews.setTextViewText(R.id.title_title, title);
        remoteViews.setImageViewBitmap(R.id.songer_pic, returnBitMap(bit));
//        remoteViews.setImageViewResource(R.id.songer_pic, R.mipmap.tingbg);
    }

    /**
     * 显示通知栏
     *
     * @param name
     */
    private void showCustomView() {

        //设置按钮事件 -- 发送广播 --广播接收后进行对应的处理

        Intent buttonPlayIntent = new Intent(ServiceReceiver.NOTIFICATION_ITEM_BUTTON_LAST); //----设置通知栏按钮广播
        PendingIntent pendButtonPlayIntent = PendingIntent.getBroadcast(this, 0, buttonPlayIntent, 0);
        remoteViews.setOnClickPendingIntent(R.id.last_music, pendButtonPlayIntent);//----设置对应的按钮ID监控


        Intent buttonPlayIntent1 = new Intent(ServiceReceiver.NOTIFICATION_ITEM_BUTTON_PLAY); //----设置通知栏按钮广播
        PendingIntent pendButtonPlayIntent1 = PendingIntent.getBroadcast(this, 0, buttonPlayIntent1, 0);
        remoteViews.setOnClickPendingIntent(R.id.paly_pause_music, pendButtonPlayIntent1);//----设置对应的按钮ID监控

        Intent buttonPlayIntent2 = new Intent(ServiceReceiver.NOTIFICATION_ITEM_BUTTON_NEXT); //----设置通知栏按钮广播
        PendingIntent pendButtonPlayIntent2 = PendingIntent.getBroadcast(this, 0, buttonPlayIntent2, 0);
        remoteViews.setOnClickPendingIntent(R.id.next_music, pendButtonPlayIntent2);//----设置对应的按钮ID监控




        builder.setContent(remoteViews).setSmallIcon(R.mipmap.ting)
                .setOngoing(true)
                .setTicker("珠穆朗玛FM");

        manager.notify(0, builder.build());
        //setLatestEventInfo

    }


    public class ServiceReceiver extends BroadcastReceiver {
        public static final String NOTIFICATION_ITEM_BUTTON_LAST
                = "com.example.notification.ServiceReceiver.last";//----通知栏上一首按钮
        public static final String NOTIFICATION_ITEM_BUTTON_PLAY
                = "com.example.notification.ServiceReceiver.play";//----通知栏播放按钮
        public static final String NOTIFICATION_ITEM_BUTTON_NEXT
                = "com.example.notification.ServiceReceiver.next";//----通知栏下一首按钮

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case NOTIFICATION_ITEM_BUTTON_LAST: //----通知栏上一首按钮响应事件
                    EventBus.getDefault().post(0);
                    break;
                case NOTIFICATION_ITEM_BUTTON_PLAY: //----通知栏播放按钮响应事件
                    if (mediaPlayer != null) {
                        if (mediaPlayer.isPlaying()) {
                            EventBus.getDefault().post(1);
                        } else {
                            EventBus.getDefault().post(2);
                        }
                    }
                    break;
                case NOTIFICATION_ITEM_BUTTON_NEXT: //----通知栏下一首按钮响应事件
                    EventBus.getDefault().post(3);
                    break;
            }
        }
    }

    /**
     * 从网址获得bitmap
     *
     * @param url
     * @return
     */
    public Bitmap returnBitMap(String url) {
        URL myFileURL;
        Bitmap bitmap = null;
        try {
            myFileURL = new URL(url);
            //获得连接
            HttpURLConnection conn = (HttpURLConnection) myFileURL.openConnection();
            //设置超时时间为6000毫秒，conn.setConnectionTiem(0);表示没有时间限制
            conn.setConnectTimeout(1000);
            //连接设置获得数据流
            conn.setDoInput(true);
            //不使用缓存
            conn.setUseCaches(false);
            //这句可有可无，没有影响
            conn.connect();
            //得到数据流
            InputStream is = conn.getInputStream();
            //解析得到图片
            bitmap = BitmapFactory.decodeStream(is);
            //关闭数据流
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bitmap;
    }

}
